package cn.wolfcode.luowowo.website.interceptor;


import cn.wolfcode.luowowo.api.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo.api.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录校验,首先获取cookie
       Cookie cookie =  CookieUtil.getCookie(request, UserInfoKeyPrefix.TOKEN_COOKIE_NAME);
        UserInfo userInfo = null;
        if(cookie != null){
            //从redis中获取userInfo对象
            userInfo = userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN, cookie.getValue());
        }
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            //判断请求方法上面是否贴有@RequireLogin注解,如果有才进行登录判断
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                //判断userInfo是否为null
                if(userInfo == null){
                    //返回到登录页面
                    response.sendRedirect("/login.html");
                    //返回false
                    return false;
                }
            }
        }
        return true;
    }
}
